package com.ljj;

import java.util.List;
import java.util.Optional;

public class ValueUtils {

    public static String getTxtValue(Value value, String path) {
        Value current = value;
        current = getValue(current, path);
        if (current == null) {
            return null;
        }
        if (current.getTxtValue().isPresent()) {
            return current.getTxtValue().get();
        }
        return null;
    }

    public static List<Value> getValues(Value value, String path) {
        Integer lastP = path.lastIndexOf(".");
        String pPath = path.substring(0, path.length() - 1);
        String lPath = path.substring(path.length() - 1);
        Value p = getValue(value, pPath);
        if (p == null) {
            return null;
        }
        if (p.getValues(lPath).isPresent()) {
            return p.getValues(lPath).get();
        }
        return null;
    }


    public static Value getValue(Value value, String path) {
        String[] paths = path.split("\\.");
        Value current = value;
        try {
            for (String p : paths) {
                Optional<Value> temp = current.getValue(p);
                if (temp.isPresent()) {
                    current = temp.get();
                } else {
                    return null;
                }
            }
        } catch (Exception e) {
            return null;
        }

        return current;
    }
}
